package com.comeon.polymorphism;

/*
 * 测试多态
 * */
public class Animal {

    public static void main(String[] args) {
//        animalCry(new Dog());
//        animalCry(new Groundhog());
//        animalCry(new Cat());
        //编译类型Animal         运行时类型Dog
        Animal a1 = new Dog();      //自动向上转型
        a1.shout();     //编译器自动a1视为Animal类型

        Dog d = (Dog)a1;    //d和a1指的还是同一个对象（即使转型了）
        d.beGood();
        //可以简写为((Dog)a1).beGood();

        //编译不会报错，但是运行会报异常：ClassCastException
        //Cat e = (Cat)a1;
        //e.shout();

        //判断是不是猫
        if (a1 instanceof Cat){
            Cat e = (Cat)a1;
            e.shout();
        }
    }

    public void shout(){}

    static void animalCry(Animal a){    //形参，相当于Animal a = new Dog()
        a.shout();  //  可以出现多态
    }
}

class Dog extends Animal{
    public void shout(){
        System.out.println("汪汪汪！");
        System.out.println("站在门口保护我方大豪宅");
    }
    public void beGood(){
        System.out.println("好好吃饭，好好休息，好好看家");
    }
}

class Groundhog extends Animal{
    public void shout(){
        System.out.println("啊~~~~~！");
        System.out.println("周末还被写进程序，我只想大叫！");
    }
}

class Cat extends Animal{
    public void shout(){
        System.out.println("喵喵，喵喵~");
        System.out.println("我的心脏怦怦跳，迷恋上你的坏笑~");
    }
}

